import { ReactElement, useState, Key, useEffect } from 'react'
import { History, Location } from 'history'
import style from './index.module.less'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import Table from '@components/table'
import { SeriesSchema, SeriesCaseSchema } from '@src/components/schema/seriesCase'
import { getColumn } from './util'
import { awaitWrap } from '@src/assets/js/tool'
import { getSeriesRequest, delCaseRequest } from './ajax'
import { Space, Button, message, Modal } from 'antd'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { addWindow } from '@src/redux/actions/tab'

const { confirm } = Modal

// 初始化数据
async function initData (seriesid: string, setSeriesData: (v: SeriesSchema) => void, setTotal: (v: number) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getSeriesRequest(seriesid))
  setLoading(false)
  if (e === null && d !== null) {
    setSeriesData(d)
    if (d.case instanceof Array) {
      setTotal(d.case.length)
    }
  }
}

// 二次确认移除案件
function confirmDel (id: string, list: SeriesCaseSchema[], setSelectedRowKeys: (v: Key[]) => void, setSelectedRows: (v: SeriesCaseSchema[]) => void, refreshData: () => void): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确认要移除这些案件吗？',
    onOk () {
      const cases = list.map(li => {
        return li.id
      })
      deleteCaseFn(cases, id, setSelectedRowKeys, setSelectedRows, refreshData).catch(e => console.error(e))
    }
  })
}

async function deleteCaseFn (cases: string[], seriesid: string, setSelectedRowKeys: (v: Key[]) => void, setSelectedRows: (v: SeriesCaseSchema[]) => void, refreshData: () => void): Promise<void> {
  const hide = message.loading('移除中')
  const [e] = await awaitWrap(delCaseRequest(cases, seriesid))
  hide()
  if (e === null) {
    message.success('移除成功').then(null, null)
    setSelectedRowKeys([])
    setSelectedRows([])
    refreshData()
  }
}

interface Props {
  meta: {
    id: string
  }
}

function Main ({meta}: Props): ReactElement {
  const dispatch = useDispatch()
  const [seriesData, setSeriesData] = useState<SeriesSchema | null>(null)
  const [dataSource, setDataSource] = useState<SeriesCaseSchema[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
  const [selectedRows, setSelectedRows] = useState<SeriesCaseSchema[]>([])
  const [params, setParams] = useState<{[k: string]: any}>({})
  function refreshData (): void {
    if (typeof meta.id === 'string') {
      initData(meta.id, setSeriesData, setTotal, setLoading).catch(e => console.error(e))
    }
  }
  useEffect(() => {
    refreshData()
  }, [meta])
  useEffect(() => {
    if (seriesData !== null && seriesData.case instanceof Array) {
      setDataSource(seriesData.case.map((li, i) => {
        li.orderno = i + 1
        return li
      }))
    }
  }, [seriesData])
  return (
    <div className={classNames(style.container, { [style.edit]: selectedRowKeys.length > 0 })}>
      <div className={style['container-header']}>
        {
          seriesData !== null && (
            <div className={style['header-line']}>
              <span className={style['header-title']}>{seriesData.serieno}</span>
              <span className={style['header-subtitle']}>{typeof seriesData.tag === 'string' && `标签：${seriesData.tag}`}</span>
              <span className={style['header-subtitle']}>{typeof seriesData.remark === 'string' && `备注：${seriesData.remark}`}</span>
            </div>
          )
        }
      </div>
      <div className={style.table}>
        <div className={style['operate-line']}>
          <span className={style['operate-title']}>案件列表</span>
          <Space>
            <Button type='primary' onClick={() => {
              dispatch(addWindow({ id: `series-case-input-${meta.id}`, title: `${seriesData?.serieno}-添加案件`, componentName: 'SeriesCaseInput', forceRefresh: true, meta: { id: meta.id } }))
              console.log(`series-case-input-${meta.id}`)
            }}>添加案件</Button>
          </Space>
        </div>
        <Table params={params} setParams={setParams} columns={getColumn()} loading={loading} total={total} dataSource={dataSource} selectable selectedRowKeys={selectedRowKeys} setSelectedRowKeys={setSelectedRowKeys} selectedRows={selectedRows} setSelectedRows={setSelectedRows} onChange={() => {}} pagenation={false} />
      </div>
      {
        selectedRowKeys.length > 0 && (
          <div className={style['btn-line']}>
            <span className={style['total-message']}>
              <span>已选择</span>
              <span className={style['total-num']}>{selectedRowKeys.length}</span>
              <span>项</span>
            </span>
            <Space>
              <Button danger ghost onClick={() => { confirmDel(meta.id, selectedRows, setSelectedRowKeys, setSelectedRows, refreshData) }}>移除</Button>
            </Space>
          </div>
        )
      }
    </div>
  )
}

export default Main
